# -*- coding: utf-8 -*-
# This code written by ChanGOGOGO
"""
黑名单
"""
import pymysql
from util import (
    logging,
    write_excel,
    per_excel_data_num,
    db_ip,
    db_port,
    db_username,
    db_password,
    excel_save_dir,
)


class ExportBlackList:
    def __init__(self, ui_data):
        self.business = ui_data.get("business")
        self.data_type = ui_data.get("data_type")
        company_id = ui_data.get("company_id")
        self.db_name = f"yicall_{company_id}"
        self.table_index = ui_data.get("business_id")
        self.conn = pymysql.connect(
            host=db_ip,
            port=db_port,
            user=db_username,
            passwd=db_password,
            charset="utf8",
        )
        self.cursor = self.conn.cursor()

    def close_db(self):
        """关闭数据库连接"""
        self.cursor.close()
        self.conn.close()

    def query_count(self):
        """查询黑名单总数"""
        sql = f"""select count(*) from {self.db_name}.b_{self.table_index}_black_number;"""
        logging.info(f"查询{self.business}的{self.data_type}总数SQL：\n{sql}")
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        count = result[0][0]
        logging.info(f"查询{self.business}的{self.data_type}共{count}条。")
        return count

    def export(self):
        total_count = self.query_count()
        if total_count < 1:
            msg = (
                f"⚠️ <font color='red'>**{self.business}**</font>的<font color='green'>{self.data_type}</font>导出失败。"
                f"原因：\n<font color='blue'>没有查询到{self.data_type}数据！</font>"
            )
            return {"code": 1, "excel_names": [], "msg": msg}
        else:
            total_batches = (total_count + per_excel_data_num - 1) // per_excel_data_num
            # 分批次查询和写入数据
            excel_names = list()
            excel_title = ["手机号码"]
            for i in range(total_batches):
                excel_data = list()
                sql = f"""select number from {self.db_name}.b_{self.table_index}_black_number 
                LIMIT {i * per_excel_data_num}, {per_excel_data_num};"""
                logging.info(
                    f"开始查询{self.business}的第[{i + 1}/{total_batches}]批次{self.data_type}：\n{sql}"
                )
                self.cursor.execute(sql)
                result = self.cursor.fetchall()
                for x in result:
                    black_phone = x[0]
                    excel_data.append([black_phone])
                if total_batches == 1:
                    file_name = f"{self.business}_{self.data_type}"
                else:
                    file_name = f"{self.business}_{self.data_type}_第{i + 1}批"
                excel_name = write_excel(
                    [[self.data_type, excel_title, excel_data]],
                    excel_save_dir,
                    file_name,
                )
                excel_names.append(excel_name)
            self.close_db()
            return {"code": 0, "excel_names": excel_names, "msg": None}


if __name__ == "__main__":
    ...
